/*
1、http接口收取邮件信息
2、邮件信息保存
3、线程定时读取邮件信息发送邮件
*/
var express = require("express");
var bodyParser = require("body-parser");
var nodemailer = require("nodemailer");
var DBM = require("./DBManager");
var config = require("./config");
DBM.connectToDB();

var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post("/sendEmail",urlencodedParser,(req,res)=>{
    console.log("get msg:",req.body);
    var body = req.body;
    var emailBody = {
        title: body.title,
        email: body.email,
        content: body.content,
        time: body.time
    }
    DBM.WriteEmail(emailBody);
    res.end("haha");
})
var server = app.listen(8081,function(){
    console.log("start server 8081")
});

//发送邮件
var transporter = nodemailer.createTransport({
    host:config.smtp,
    port: 465,
    secure: true,
    auth:{
        user:config.mailFrom,
        pass:config.mailPwd
    }
});
function sendEmail(){
    DBM.ReadEmail((emailList)=>{
        console.log("get email",emailList)
        if(emailList != null && emailList.length > 0){
            console.log("get emails ",emailList.length);
            for(var i=0;i<emailList.length;i++){
                var email = emailList[i];
                var mailOptions = {
                    from:config.mailFrom,
                    to:email.email,
                    subject:email.title,
                    text:email.content
                }
                try{
                    transporter.sendMail(mailOptions,function(err,info){
                        if(err){
                            console.log("send Fail",err);
                            return;
                        }
                        console.log("send Success:");
                        DBM.SendFinish(email.id);
                    });
                }catch(err){
                    console.log("try error",err);
                }
            }
        }
    });
    
}
const setInterval_now = (func, interval)=>{
    func();
    return setInterval(func,interval);
}
//定时查找有无邮件需要发送
var timer = null;
timer && clearInterval(timer);
timer = setInterval_now(sendEmail,1000*60*60);